import React, { useState } from "react";
import {
  View,
  Text,
  TouchableOpacity,
  StyleSheet,
  ScrollView,
  Image,
} from "react-native";
import { Ionicons } from "@expo/vector-icons";
import { useTheme } from "@/contexts/ThemeContext";
import { Divider, Switch, Input } from "@rneui/themed";
import * as ImagePicker from "expo-image-picker";
import { router } from "expo-router";
import AlertService from "@/components/Global/Alert/service";
import {createGroup} from "@/services/api/group";
import {GroupCreateTransferType, GroupCreateType, GroupType} from "@/types/group";

const GroupCreate = () => {
  const { colors } = useTheme();

  // 群聊表单数据
  const [groupData, setGroupData] = useState<GroupCreateType>({
    name: "",
    avatar: {},
    description: "",
    type: 'private'
  });

  // 展开/折叠群描述
  const [descriptionExpanded, setDescriptionExpanded] = useState(false);

  // 处理头像选择
  const handleSelectAvatar = async () => {
    try {
      const permissionResult =
        await ImagePicker.requestMediaLibraryPermissionsAsync();

      if (!permissionResult.granted) {
        AlertService.showAlert("warning", "请在设置中允许应用访问您的相册");
        return;
      }

      const result = await ImagePicker.launchImageLibraryAsync({
        mediaTypes: ImagePicker.MediaTypeOptions.Images,
        allowsEditing: true,
        aspect: [1, 1],
        quality: 0.8,
      });

      if (!result.canceled && result.assets && result.assets.length > 0) {
        const asset = result.assets[0];
        const uri = asset.uri;
        const fileName =  asset.fileName || `file_${uri.split("/").pop()}`; // 防止 fileName 为 undefined
        const fileType = asset.mimeType || "application/octet-stream"; // 更健壮
        setGroupData((prev) => ({
          ...prev,
          avatar: {
              uri,
              name: fileName,
              type: fileType,
          },
        }));
      }
    } catch (error) {
      console.error("选择头像时出错:", error);
      AlertService.showAlert("error", "选择头像时出现错误");
    }
  };

  // 创建群聊
  const handleCreateGroup = async () => {
    // 验证群名称是否为空
    if (!groupData.name.trim()) {
      AlertService.showAlert("warning", "请输入群聊名称");
      return;
    }
    //创建群聊api
    const formData = new FormData();

    formData.append("file", groupData.avatar);
    console.log(groupData.avatar);
    const data : GroupCreateTransferType = {...groupData}
    formData.append("data", JSON.stringify(data));
    console.log(formData);
    await createGroup(formData)
    router.canGoBack && router.back();
    AlertService.showAlert('success', '群聊创建成功');
  };

  const styles = StyleSheet.create({
    container: {
      flex: 1,
      backgroundColor: colors.backgroundLight,
    },
    card: {
      backgroundColor: colors.background,
      borderRadius: 8,
      marginHorizontal: 16,
      marginVertical: 8,
      padding: 16,
    },
    inputGroup: {
      marginBottom: 10,
    },
    inputLabel: {
      fontSize: 15,
      color: colors.text.primary,
      marginBottom: 6,
    },
    input: {
      borderWidth: 1,
      borderColor: colors.border.light,
      borderRadius: 8,
      backgroundColor: colors.inputBackground,
    },
    inputContainer: {
      borderBottomWidth: 0,
      paddingHorizontal: 0,
    },
    inputStyle: {
      fontSize: 15,
      color: colors.text.primary,
      height: 40, // 添加固定高度
    },
    switchContainer: {
      flexDirection: "row",
      justifyContent: "space-between",
      alignItems: "center",
      paddingVertical: 10,
    },
    switchLabel: {
      fontSize: 15,
      color: colors.text.primary,
    },
    switchNote: {
      fontSize: 12,
      color: colors.text.secondary,
      marginTop: 4,
    },
    avatarContainer: {
      alignItems: "center",
      marginVertical: 16,
    },
    avatar: {
      width: 80,
      height: 80,
      borderRadius: 40,
      marginBottom: 8,
    },
    avatarText: {
      color: colors.primary,
      fontSize: 14,
    },
    descriptionHeader: {
      flexDirection: "row",
      justifyContent: "space-between",
      alignItems: "center",
      marginBottom: descriptionExpanded ? 8 : 0,
    },
    descriptionInput: {
      height: 100,
    },
    buttonContainer: {
      paddingHorizontal: 16,
      paddingBottom: 20,
    },
    createButton: {
      backgroundColor: colors.primary,
      paddingVertical: 12,
      borderRadius: 8,
      alignItems: "center",
    },
    buttonText: {
      color: "#FFFFFF",
      fontWeight: "bold",
      fontSize: 16,
    },
    divider: {
      height: 0.5,
      backgroundColor: colors.border.divider,
      marginVertical: 10,
    },
  });

  return (
    <View style={styles.container}>
      <ScrollView>
        <View style={styles.card}>
          {/* 群头像 */}
          <TouchableOpacity
            style={styles.avatarContainer}
            onPress={handleSelectAvatar}
          >
            <Image source={{ uri: groupData.avatar.uri }} style={styles.avatar} />
            <Text style={styles.avatarText}>点击设置群头像</Text>
          </TouchableOpacity>

          {/* 群名称 */}
          <View style={styles.inputGroup}>
            <Text style={styles.inputLabel}>群聊名称</Text>
            <Input
              placeholder="请输入群聊名称（必填）"
              placeholderTextColor={colors.text.hint}
              value={groupData.name}
              onChangeText={(text) =>
                setGroupData((prev) => ({ ...prev, name: text }))
              }
              maxLength={20}
              inputStyle={styles.inputStyle}
              inputContainerStyle={styles.inputContainer}
              containerStyle={[styles.input, { height: 45 }]} // 添加固定高度
            />
          </View>

          <Divider style={styles.divider} />

          {/* 群描述(可折叠) */}
          <View style={styles.inputGroup}>
            <TouchableOpacity
              style={styles.descriptionHeader}
              onPress={() => setDescriptionExpanded(!descriptionExpanded)}
            >
              <Text style={styles.inputLabel}>群描述</Text>
              <Ionicons
                name={descriptionExpanded ? "chevron-up" : "chevron-down"}
                size={18}
                color={colors.text.secondary}
              />
            </TouchableOpacity>

            {descriptionExpanded && (
              <Input
                placeholder="请输入群描述（选填）"
                placeholderTextColor={colors.text.hint}
                value={groupData.description}
                onChangeText={(text) =>
                  setGroupData((prev) => ({ ...prev, description: text }))
                }
                multiline
                maxLength={200}
                inputStyle={[styles.inputStyle, { textAlignVertical: "top" }]}
                inputContainerStyle={styles.inputContainer}
                containerStyle={[styles.input, styles.descriptionInput]}
              />
            )}
          </View>

          <Divider style={styles.divider} />

          {/* 群访问类型 */}
          <View>
            <View style={styles.switchContainer}>
              <Text style={styles.switchLabel}>公开群聊</Text>
              <Switch
                value={groupData.type === GroupType.PUBLIC}
                onValueChange={(value) =>
                  setGroupData((prev) => ({ ...prev, type: value ? GroupType.PUBLIC : GroupType.PRIVATE }))
                }
                color={colors.primary}
              />
            </View>
            <Text style={styles.switchNote}>
              {groupData.type === GroupType.PUBLIC
                ? "任何人都可以搜索并查看此群聊"
                : "仅群成员可以访问此群聊"}
            </Text>
          </View>
        </View>
      </ScrollView>

      {/* 创建按钮 */}
      <View style={styles.buttonContainer}>
        <TouchableOpacity
          style={styles.createButton}
          onPress={handleCreateGroup}
        >
          <Text style={styles.buttonText}>创建群聊</Text>
        </TouchableOpacity>
      </View>
    </View>
  );
};

export default GroupCreate;
